import React, { useCallback, useEffect, useState } from 'react'
import { List, Tag, Space, PullToRefresh, InfiniteScroll } from 'antd-mobile'
import http from '../helper/http'
import { PageModel } from '@/models/PageModel'
import { WorkCountModel } from '../models/WorkCountModel'
import wcheader from './WorkCountFC/WorkCountHeader'
import dayjs from 'dayjs'
import { useNavigate } from 'react-router-dom'
import qs from 'qs'

export default (props: { mode: 'all' | 'mine' }) => {
    const groupby = { all: ['YYYY-MM'], mine: ['YYYY-MM-DD'] }[props.mode] ?? ['YYYY-MM']
    const keywords = { all: '', mine: localStorage.getItem('username') }[props.mode] ?? ''
    const dt1date = dayjs().date(1).toDate()
    const dt2date = dayjs().date(1).add(1, 'month').add(-1, 'day').toDate()

    const [page, setPage] = useState<PageModel>({ page: 1, size: 20, groupby, keywords, date1: dt1date, date2: dt2date })

    const [list, setList] = useState<WorkCountModel[]>([]);
    const [hasMore, setHasMore] = useState(true)

    const loadData = () => {

        const params = Object.assign({}, page, {
            date1: dayjs(page.date1).format('YYYY-MM-DD'),
            date2: dayjs(page.date2).format('YYYY-MM-DD'),
            groupby: page.groupby[0],
            keywords: encodeURI(page.keywords),
            sidx: props.mode === 'all' ? 'WORK_COUNT' : 'TIME_STR',
            sort: 'desc'
        })

        // 如果是从排名界面进来的
        const hashstr = location.hash;
        const param = hashstr.slice(hashstr.indexOf('?') + 1)
        const queryParam = qs.parse(param) as { dept: string, name: string, day: string }
        if (queryParam.name) {
            params.keywords = encodeURI(queryParam.name)
        }


        return http.get('/work-list', { params }).then(res => {
            const data = res.data
            setHasMore(data.rows.length === page.size)
            return Promise.resolve(data)
        });
    }

    // useEffect(() => {
    //     onRefresh();
    // }, [])

    const onRefresh = () => {
        page.page = 1

        setPage(page)

        return loadData().then((res) => {
            setList(res.rows)
        })
    }

    const onSearch = (param: PageModel) => {
        page.keywords = param.keywords
        page.groupby = param.groupby
        page.date1 = param.date1
        page.date2 = param.date2
        page.page = 1
        setPage(page)
        return loadData().then((res) => {
            setList(res.rows)
        })
    }

    const loadMore = (isRetry: boolean): Promise<void> => {
        if (list.length === 0) {
            page.page = 1
        } else {
            page.page += 1
        }
        setPage(page)

        return loadData().then((res) => {
            setList([...list, ...res.rows])
        })
    }
    const navigate = useNavigate();

    const gotoDetail = (row: WorkCountModel) => {
        if (props.mode === 'mine') {
            navigate(`/home/mywork-detail?dept=${row.DEPTNAME}&name=${row.USER_NAME}&day=${row.TIME_STR_SHOW}`)
        }
        else if (props.mode === 'all') {
            navigate(`/home/mywork?name=${row.USER_NAME}&day=${row.TIME_STR_SHOW}`)
        }
    }


    const headertitle = { all: '本月工作量排名', mine: `本月工作量汇总` }[props.mode] ?? ''
    return (
        <>
            <PullToRefresh onRefresh={onRefresh}>
                <List mode='default'
                    header={
                        wcheader(headertitle, props.mode, page, (param => {
                            onSearch(param)
                        }))
                    }>
                    {list.map((item, index: number) => (
                        <List.Item key={index} extra='详情' clickable
                            description={
                                <span style={{ display: 'block', marginTop: '10px' }}>{item.TIME_STR_SHOW}</span>
                            } onClick={() => gotoDetail(item)}>
                            <Space>
                                <Tag color='primary' style={{ '--border-radius': '50%' }}>{index + 1}</Tag>
                                <Tag style={{ width: '50px' }} color='primary'>{item.USER_NAME}</Tag>
                                <Tag style={{ width: '80px' }} color='success'>{`工作量:${item.WORK_COUNT}`}</Tag>
                                <Tag style={{ width: '80px' }} color='success'>{`小时数:${item.WORK_TIME}`}</Tag>
                            </Space>
                        </List.Item>
                    ))}
                </List>
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </PullToRefresh>
        </>
    )
}